﻿using BodaNetCommunications.Commbase;
using BodaNetCommunications.Cores;
using BodaNetCommunications.Utilities.Attributes;
using BodaNetCommunications.Utilities.ComTypes;
using BodaNetCommunications.Utilities.Results;

namespace BodaNetCommunications.McComs
{
    [ProtocolTypeAttribute(ProtocolType.McQnA3E)]
    public class McCommService : CommReadWrite, IMcCommService
    {

        public McQnA3E McDevice { get; private set; }

        public ConnectionOptions Options { get; private set; }

        public bool IsConnected => McDevice != null && McDevice.IsConnected;

        public McCommService()
        {
            base._byteTransform = new McByteTransformBase();
          
        }

        public BodaResult Connect(ConnectionOptions connectionOptions)
        {
            if (IsConnected)
            {
                BodaResult bodaResult = new BodaResult();
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"Mc【{Options.Ip}:{Options.Port}】的连接已经在线，不需要重复连接";
                return bodaResult;
            }

            Options = connectionOptions;
            McDevice = new McQnA3E();

            return McDevice.Connect(Options);
        }

        public void Disconnect()
        {
            McDevice?.Disconnect();
        }

        public override BodaResult<short[]> ReadInt16(string address, ushort length)
        {
            var words = GetWordLength(address, length, 1);
            var readRes = Read(address, words);
            return ByteTransformHelper.GetResultFromBytes(readRes, (byte[] m) => _byteTransform.TransInt16(m, 0, length));
        }

        /// <summary>
        /// 重写基础数据的读取功能
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="length">数据个数</param>
        /// <returns></returns>
        public override BodaResult<byte[]> Read(string address, ushort length)
        {
            BodaResult<byte[]>? readResult = McDevice.ReadBytes(address, length);
            return readResult;
        }


        public override BodaResult Write(string address, byte[] values)
        {
            BodaResult readResult = McDevice.Write(address, values);
            return readResult;
        }

        public BodaResult SendMsgc(byte[] bytes, int timeout = 1500)
        {
            throw new NotImplementedException();
        }

        public BodaResult<byte> ReceiveMsg(int timeout = 2000, int bytesLen = 1024)
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            this.Disconnect();
        }
    }
}
